package com.mybatis.student;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class UserManage {
    public static void main(String[] args) throws IOException {
        SqlSession session = null; // 声明在 try 外部
        try {
            InputStream inputStream = Resources.getResourceAsStream("config/student-config.xml");
            SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(inputStream);
            session = ssf.openSession(); // 初始化 session

            // 查询所有用户
            List<User> list = session.selectList("UserMapper.queryAllUser");
            System.out.println("查询所有的用户记录");
            User[] users = list.toArray(new User[0]);
            for (User user : users) {
                System.out.println(user);
            }

            // 插入一条用户记录
            User newUser = new User();
            newUser.setNumber("20220102002");
            newUser.setPassword("234561");
            newUser.setIdentity("student");

            System.out.println("插入一条用户记录");
            System.out.println(newUser);
            session.insert("UserMapper.addUser", newUser);

            // 查询账号为20220102002的用户
            User resultUser = session.selectOne("UserMapper.queryUserByNum", "20220102002");
            System.out.println("查询账号为20220102002");
            System.out.println(resultUser);

            session.commit(); // 提交事务
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈信息
        } finally {
            if (session != null) { // 检查 session 是否为空
                session.close(); // 关闭会话

                System.out.println("测试数据库连接...");
                InputStream inputStream = Resources.getResourceAsStream("config/student-config.xml");
                SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(inputStream);
                session = ssf.openSession();
                if (session != null) {
                    System.out.println("数据库连接成功！");
                } else {
                    System.out.println("数据库连接失败！");
                }

            }
        }
    }
}
